<template>
  <div class="phoneNav">
    <ul
      ref="ulTarget"
      class="relative flex items-center overflow-y-auto text-xl text-zinc-600 px-3"
    >
      <li
        class="flex-shrink-0 absolute rounded-lg h-[16px] bg-slate-700 z-[-1]"
        :style="sliderStyle"
      ></li>
      <li
        class="fixed right-0 shadow-l-white w-8 h-[25px] flex items-center bg-white"
      >
        <m-svg-icon icon="hamburger"></m-svg-icon>
      </li>
      <li
        v-for="(item, index) in categoryData"
        :key="item.id"
        class="mr-2 flex-shrink-0 mt-1 mb-1 last:mr-10 px-2 py-2"
        :class="{
          'text-zinc-100': $store.getters.currentCategoryIndex === index,
        }"
        :ref="setItemRef"
        @click="onItemClick(index)"
      >
        {{ item.name }}
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, onBeforeUpdate, watch, onMounted } from "vue";
import { useScroll } from "@vueuse/core";
import { useStore } from "vuex";

defineProps({
  categoryData: {
    type: Array,
    required: true,
  },
});
const sliderStyle = ref({
  with: "12px",
  transform: "translateX(0px)",
});

/**保存当前选中的元素下标
 * 因为是PC端和移动端的导航栏是一样的，数据共享用VUEX
 */
const store = useStore();
const onItemClick = (index) => {
  store.commit("category/setCategorysCurrentItem", index);
};

/**当dom发生变化的时候，itemRefs会被不断填满导致重复，需要在onBeforeUpdate数据更新时情况原来的数组
 * 获取填充的所有 item 元素
 *  */
let liArray = [];
const setItemRef = (el) => {
  liArray.push(el);
};
onBeforeUpdate(() => {
  liArray = [];
});
/**
 * ul偏移的位置
 */
// 获取 ul 元素，以计算偏移位置
const ulTarget = ref(null);
const { x: ulScrollLeft } = useScroll(ulTarget);
const changeSliderPositioin = () => {
  // 获取选中元素的 left、width
  const { left, width } =
    liArray[store.getters.currentCategoryIndex].getBoundingClientRect();
  // 为 sliderStyle 设置属性
  sliderStyle.value = {
    // ul 横向滚动位置 + 当前元素的 left 偏移量-ul本身左侧的paddiing 10px
    transform: `translateX(${ulScrollLeft.value + left - 12 + "px"})`,
    width: width + "px",
  };
};
onMounted(() => {
  store.commit("category/setCategorysCurrentItem", 0);
  changeSliderPositioin();
});
watch(
  () => store.getters.currentCategoryIndex,
  () => {
    changeSliderPositioin();
  }
);
</script>

<style lang="scss" scoped></style>
